from flask import render_template, jsonify, request, session, g

from app.models.models import News, Comment, Collection
from app.utils.common.common import login_user_data
from app.views.news import news_blu
from app import db


# @news_blu.route("/Comic_consulting")
# @login_user_data
# def Comic_consulting():
#     # 1. 查询点击排行的前6个数据
#     print("123456")
#     rank_news = db.session.query(News).order_by(News.clicks.desc()).limit(6)  # 从news数据表中查询点击最高的6个数据
#     print(rank_news)
#     # 如果用户登录成功，那么它就有session值，取出这些值来
#     user = g.user
#
#     return render_template("index/Comic_consulting.html", rank_news=rank_news, user=user)


# @news_blu.route("/newslist")
# def newslist():
#
#     # 0. 提取数据
#     page = request.args.get("page", 1)
#     cid = request.args.get("cid", 0)
#     per_page = request.args.get("per_page", 10)
#
#     page = int(page) if page.isalnum() else 1
#     cid = int(cid) if cid.isalnum() else 0
#     per_page = int(per_page) if per_page.isalnum() else 10
#
#     # 1. 先从数据库中查询
#     if cid == 0:
#         paginate = db.session.query(News).filter(News.status == 0).order_by(News.create_time.desc()).paginate(page, per_page, False)
#     else:
#         paginate = db.session.query(News).filter(News.category_id == cid, News.status == 0).paginate(page, per_page, False)
#     news_list = paginate.items  # 查询出来的对象组成的列表
#
#     # 2. 将查询出来的数据模型对象转化为需要的字典格式
#     ret = {
#         "totalPage": paginate.pages,
#         "newsList": [news.to_dict() for news in news_list]
#     }
#
#     # 3. 将字典格式的数据转换为json格式，返回给前端
#     # return jsonify(news_list)  # 这种方式不能使用，因为news中是News类的实例对象，使用jsonify不能将其转换为json格式，
#     # 所以我们需要，先将news对象转化为普通的字典类型，然后再转化为json
#     return jsonify(ret)
#
#
# @news_blu.route("/detail/<int:news_id>")
# @login_user_data
# def detail(news_id):
#     # 如果用户登录成功，那么它就有session值，取出这些值来
#     user_id = session.get("user_id")
#     nick_name = session.get("nick_name")
#
#     # 根据id来查询新闻
#     news = db.session.query(News).filter(News.id == news_id).first()
#
#     # 通过SQLAlchemy查询出新闻的作者
#     news_author = news.user
#     news_author.news_num = news_author.news.count()
#
#     # print(news_author.followers)
#     # 获取作者所有的粉丝数
#     news_author.followers_num = news_author.followers.count()
#
#     # 判断当前用户是否可以关注这个作者
#     if user_id in [x.id for x in news_author.followers]:
#         news_author.can_follow = False
#     else:
#         news_author.can_follow = True
#
#     # 查询点击靠前的前6个新闻
#     rank_news = db.session.query(News).order_by(News.clicks.desc()).limit(6)  # 从news数据表中查询点击最高的6个数据
#
#     # 判断当前用户是否已经收藏过此新闻
#     if g.user and (g.user.id in [x.id for x in news.collection_user]):
#         print("收藏过.....")
#         g.user.can_collect = False
#     else:
#         g.user.can_collect = True
#
#     # 得到当前新闻评论的所有信息
#     comments = [x.to_basic_dict() for x in news.comments.order_by(Comment.create_time.desc())]
#
#     # 获取当前用户所有的点赞的评论
#     like_comments = [x.to_basic_dict() for x in g.user.like_comments]
#
#     return render_template("index/detail.html",
#                            news=news,
#                            rank_news=rank_news,
#                            user_id=user_id,
#                            nick_name=nick_name,
#                            news_author=news_author,
#                            user=g.user,
#                            comments=comments,
#                            like_comments=like_comments
#                            )
@news_blu.route("/news/collect", methods=["POST"])
@login_user_data
def collect():
    print("023-")
    # 1. 取参数
    action = request.json.get("action")
    news_id = request.json.get("news_id")

    if not all([action, news_id]):
        ret = {
            "errno": 5001,
            "errmsg": "缺少参数"
        }

        return jsonify(ret)

    # 2. 把当前用户的id取出来
    if not g.user:
        ret = {
            "errno": 5002,
            "errmsg": "未登录"
        }

        return jsonify(ret)

    if action == "do":
        # 3. 此时就有了新闻的id和用户的id,插入数据库
        collect = Collection()
        collect.news_id = news_id
        collect.user_id = g.user.id
        try:
            db.session.add(collect)
            db.session.commit()
            ret = {
                "errno": 0,
                "errmsg": "收藏成功"
            }
        except Exception as ret:
            print("保存文章收藏时，数据库插入失败...", ret)
            ret = {
                "errno": 5003,
                "errmsg": "收藏失败"
            }

        # 5. 返回json数据
        return jsonify(ret)
    elif action == "undo":
        collect = db.session.query(Collection).filter(Collection.user_id == g.user.id,
                                                      Collection.news_id == news_id).first()
        if collect:
            db.session.delete(collect)
            db.session.commit()
            ret = {
                "errno": 0,
                "errmsg": "取消收藏成功"
            }

        else:
            ret = {
                "errno": 5004,
                "errmsg": "取消收藏失败"
            }

        return jsonify(ret)